//
//  HTRegisterTruckMainVC.m
//  TruckDriver
//
//  Created by Ting Han on 2017/9/28.
//  Copyright © 2017年 Ting Han. All rights reserved.
//

#import "HTRegisterTruckMainVC.h"
#import "HTNormalCell.h"
#import "HTAddOrderCell.h"
#import "HTRegisterLineHeader.h"
#import "HTSafeTipsCell.h"
#import "UIImageView+WebCache.h"

#import "HTNormalModel.h"
#import "HTNormalTitleModel.h"
#import "HTNormalTitleCell.h"
//选择车牌类型，车型，车长
#import "HTChoseViewController.h"
//输入载重
#import "HTInputViewController.h"
//车牌号
#import "HTTruckLicenseView.h"
#import "HTMineViewController.h"
#import "HTImageClipViewController.h"

@interface HTRegisterTruckMainVC ()<UITableViewDelegate,UITableViewDataSource,UIImagePickerControllerDelegate,UINavigationControllerDelegate,HTChoseViewControllerDelegate,HTInputViewControllerDelegate,HTTruckLicenseViewDelegate,HTImageClipViewControllerDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *safeBottomHeight;
@property (nonatomic,strong) NSArray *dataSource;
@property (nonatomic,weak) UIImageView *headImageView;

@property (nonatomic,strong) NSString *license;
@property (nonatomic,strong) NSString *heavy;
@property (nonatomic,strong) NSString *truckType;
@property (nonatomic,strong) NSString *length;
@property (nonatomic,strong) NSString *cardType;
@property (nonatomic,strong) NSString *picUrl;
@property (nonatomic,assign) NSInteger regist;

@end

@implementation HTRegisterTruckMainVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"车辆信息";
    self.safeBottomHeight.constant = IPHONE_SAFEBOTTOMAREA_HEIGHT;
   self.regist = self.mineModel ? [self.mineModel.regist integerValue] : 0;
    if (!(self.regist == 0)){
        [self netLoadUserMessage];
    }
    [self configTableView];
    [self configData];
}
- (void)configData{
    if (self.regist == 0) {//未认证
        self.dataSource =@[[HTNormalTitleModel normalModelWithTitle:@"车牌类型" detital:nil]
                           ,[HTNormalTitleModel normalModelWithTitle:@"车牌号码" detital:nil]
                           ,[HTNormalTitleModel normalModelWithTitle:@"车型" detital:nil]
                           ,[HTNormalTitleModel normalModelWithTitle:@"车长" detital:nil]
                           ,[HTNormalTitleModel normalModelWithTitle:@"载重" detital:nil]];
    }else{//已经有数据
        self.dataSource =@[[HTNormalTitleModel normalModelWithTitle:@"车牌类型" detital:[self.mineModel.numbertype isEqualToString:@"1"]?@"蓝色车牌":@"黄色车牌"]
                           ,[HTNormalTitleModel normalModelWithTitle:@"车牌号码" detital:self.mineModel.carids]
                           ,[HTNormalTitleModel normalModelWithTitle:@"车型" detital:self.mineModel.types]
                           ,[HTNormalTitleModel normalModelWithTitle:@"车长" detital:[NSString stringWithFormat:@"%@米",self.mineModel.length]]
                           ,[HTNormalTitleModel normalModelWithTitle:@"载重" detital:[NSString stringWithFormat:@"%@吨",self.mineModel.loads]]];
        self.cardType = self.mineModel.numbertype;
        self.license = self.mineModel.carids;
        self.length = self.mineModel.length;
        self.heavy = self.mineModel.loads;
        self.truckType = self.mineModel.types;
        self.picUrl = self.mineModel.license;
    }
    
}
- (void)configTableView{
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.tableFooterView=[[UIView alloc]init];
    self.tableView.backgroundColor = kBackgroundColor;
    [self.tableView registerNib:[UINib nibWithNibName:@"HTNormalCell" bundle:nil] forCellReuseIdentifier:normalCell];
     [self.tableView registerNib:[UINib nibWithNibName:@"HTNormalTitleCell" bundle:nil] forCellReuseIdentifier:normalTitleCell];
    [self.tableView registerNib:[UINib nibWithNibName:@"HTAddOrderCell" bundle:nil] forCellReuseIdentifier:addOrderCell];
    [self.tableView registerNib:[UINib nibWithNibName:@"HTSafeTipsCell" bundle:nil] forCellReuseIdentifier:safeTipsCell];
    
    
}
#pragma mark --- tableView
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (self.regist == 2) {
        return 3;
    }
    return 4;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 5;
    }
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    switch (indexPath.section) {
        case 0:
            return 50;
            break;
        case 1:
            return 80;
            break;
        case 2:
            return 100;
            break;
        case 3:
            return kWidth(60);
            break;
        default:
            break;
    }
    return 20;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0)  {
        return 100;
    }
    return 20;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 3) { //申请认证
        HTAddOrderCell *cell = [tableView dequeueReusableCellWithIdentifier:addOrderCell forIndexPath:indexPath];
        cell.backgroundColor = kBackgroundColor;
        [cell.addBtn setTitle:@"申请认证" forState:UIControlStateNormal];
        [cell.addBtn addTarget:self action:@selector(didNextBtn:) forControlEvents:UIControlEventTouchUpInside];
        return cell;
    }else if(indexPath.section == 2) {//安全提示
        HTSafeTipsCell *cell = [tableView dequeueReusableCellWithIdentifier:safeTipsCell forIndexPath:indexPath];
        return cell;
    }else if(indexPath.section == 0){
        HTNormalTitleCell *cell = [tableView dequeueReusableCellWithIdentifier:normalTitleCell forIndexPath:indexPath];
        cell.normalModel = self.dataSource[indexPath.row];
        return cell;
    }
    HTNormalCell *cell = [tableView dequeueReusableCellWithIdentifier:normalCell forIndexPath:indexPath];
    cell.normalModel = [HTNormalModel normalModelWithTitle:@"行驶证" height:80 imageName:@"bg_license_car"];
    cell.imageWidth.constant = 90;
    self.headImageView = cell.rightImageView;
     [self.headImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",self.mineModel.license]] placeholderImage:[UIImage imageNamed:@"bg_license_car"]options:SDWebImageRefreshCached];
    return cell;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
   if (section == 0)  {
        HTRegisterLineHeader *header = [[HTRegisterLineHeader alloc]initWithFrame:CGRectMake(0, 0, kHTScreenWidth, 100)];
        header.type = RegisterLineHeaderTypeTwo;
        return header;
    }
    UIView *view = [[UIView alloc]initWithFrame:tableView.tableHeaderView.bounds];
    view.backgroundColor = kBackgroundColor;
    return view;
}
#pragma mark --- 点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.regist == 2) {
        return;
    }
    if(indexPath.section == 1){
        [self callActionSheetWithMessage:@"请您上传真实的行驶证" tag:111];
    }else if(indexPath.section == 0){
        switch (indexPath.row) {
            case 0://车牌类型
            {
                HTChoseViewController *chose = [[HTChoseViewController alloc]init];
                chose.type = ChoseTypeCard;
                chose.delegate = self;
                [self.navigationController pushViewController:chose animated:YES];
            }
                break;
            case 1://车牌号码
            {
                HTTruckLicenseView *license =  [[HTTruckLicenseView alloc]init];
                license.delegate = self;
                [license showView];
            }
                break;
            case 2://车型
            {
                HTChoseViewController *chose = [[HTChoseViewController alloc]init];
                chose.type = ChoseTypeTruck;
                chose.delegate = self;
                [self.navigationController pushViewController:chose animated:YES];
            }
                break;
            case 3://车长
            {
                HTChoseViewController *chose = [[HTChoseViewController alloc]init];
                chose.type = ChoseTypeLength;
                chose.delegate = self;
                [self.navigationController pushViewController:chose animated:YES];
            }
                break;
            case 4://载重
            {
                HTInputViewController *input = [[HTInputViewController alloc]init];
                input.type = InputTypeHeavy;
                input.delegate = self;
                [self.navigationController pushViewController:input animated:YES];
                
            }
                break;
            default:
                break;
        }
    }
}
#pragma mark -- 图片处理
- (void)callActionSheetWithMessage:(NSString *)message tag:(NSInteger)tag{
    [UIAlertController actionSheetStyleShowInController:self title:@"温馨提示" message:message alertActionsBlock:^(NSMutableArray<UIAlertAction *> *alertActions) {
        
        [alertActions addObject:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action){
            UIImagePickerController *PickerImage = [[UIImagePickerController alloc]init];
            PickerImage.view.tag = tag;
            PickerImage.sourceType = UIImagePickerControllerSourceTypeCamera;
            PickerImage.allowsEditing = NO;
            PickerImage.delegate = self;
            [self presentViewController:PickerImage animated:YES completion:nil];
        }]];
        [alertActions addObject:[UIAlertAction actionWithTitle:@"本地相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            UIImagePickerController *PickerImage = [[UIImagePickerController alloc]init];
            PickerImage.view.tag = tag;
            PickerImage.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            PickerImage.allowsEditing = NO;
            PickerImage.delegate = self;
            [self presentViewController:PickerImage animated:YES completion:nil];
        }]];
        [alertActions addObject:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    } completion:^{
        
    }];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}


- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    UIImage *portraitImg = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
    if(picker.view.tag == 111){
        [self CropImageViewControllerWithImage:portraitImg Frame:CGRectMake(0, kWidth(90), kHTScreenWidth, kHTScreenWidth/4*3) WithIndex:picker.view.tag withPicker:picker];
    }
}
- (void)CropImageViewControllerWithImage:(UIImage*)portraitImg Frame:(CGRect )rect WithIndex:(NSInteger )index withPicker:(UIImagePickerController *)picker {
    HTImageClipViewController *imgCropperVC = [[HTImageClipViewController alloc] initWithImage:portraitImg cropFrame:rect limitScaleRatio:3.0];
    imgCropperVC.delegate = self;
    imgCropperVC.tag = index;
    [picker pushViewController:imgCropperVC animated:NO];
}
- (void)imageCropperDidCancel:(HTImageClipViewController *)clipViewController{
    [clipViewController dismissViewControllerAnimated:YES completion:nil];
}
- (void)imageCropper:(HTImageClipViewController *)clipViewController didFinished:(UIImage *)editedImage{
    switch (clipViewController.tag) {
        case 111:
        {
           
            self.headImageView.image = editedImage;
            [self netUpLoadPictureType:@"drivercar" image:editedImage];
            [clipViewController dismissViewControllerAnimated:YES completion:nil];
        }
            break;
        default:
            break;
    }
    
}


#pragma mark --
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView == self.tableView)
    {
        CGFloat sectionHeaderHeight = 100; //sectionHeaderHeight
        if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0) {
            scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
        } else if (scrollView.contentOffset.y>=sectionHeaderHeight) {
            scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
        }
    }
}
#pragma mark --- delegate
- (void)didChoseItem:(NSString *)itemStr withType:(ChoseType)type{
    if (type == ChoseTypeLength) {
        HTNormalTitleCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:3 inSection:0]];
        cell.detialLabel.text = [NSString stringWithFormat:@"%@米",itemStr];
        self.length = itemStr;
    }else if(type == ChoseTypeTruck){
        HTNormalTitleCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:0]];
        cell.detialLabel.text = itemStr;
        self.truckType = itemStr;
    }else if(type == ChoseTypeCard){
        HTNormalTitleCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
        cell.detialLabel.text = itemStr;
        if ([itemStr isEqualToString:@"蓝色车牌"]) {
            self.cardType = @"1";
        }else{
            self.cardType = @"2";
        }
    }
}

//载重
- (void)didInputMessage:(NSString *)message withType:(InputType)type{
    if (type == InputTypeHeavy ) {//载重
        HTNormalTitleCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:4 inSection:0]];
        cell.detialLabel.text = [NSString stringWithFormat:@"%@吨",message];
        self.heavy = message;
    }
}
//车牌号
- (void)didGotCallBackLicense:(NSString *)title{
    HTNormalTitleCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
    cell.detialLabel.text = title;
    self.license = title;
}
#pragma mark --- 网络请求
//点击申请认证
- (void)didNextBtn:(id)sender{
    if (self.name == nil || self.name.length <= 0) {
        [HTShowUtil showMessage:@"请输入姓名"];
        return;
    }
    if (self.idCard == nil || self.idCard.length <= 0) {
        [HTShowUtil showMessage:@"请输入身份证号"];
        return;
    }
    if (self.cardType == nil || self.cardType.length <= 0) {
        [HTShowUtil showMessage:@"请选择车牌类型"];
        return;
    }
    if (self.license == nil || self.license.length <= 0) {
        [HTShowUtil showMessage:@"请输入车牌号码"];
        return;
    }
    if (self.truckType == nil || self.truckType.length <= 0) {
        [HTShowUtil showMessage:@"请选择车型"];
        return;
    }
    if (self.length == nil || self.length.length <= 0) {
        [HTShowUtil showMessage:@"请选择车长"];
        return;
    }
    if (self.heavy == nil || self.heavy.length <= 0) {
        [HTShowUtil showMessage:@"请输入载重"];
        return;
    }
    if (self.picUrl == nil || self.picUrl.length <= 0) {
        [HTShowUtil showMessage:@"请上传驾驶证"];
        return;
    }
    [self netLoadRegister];
}
- (void)netUpLoadPictureType:(NSString *)type image:(UIImage *)image{
    [self startHud];
    [HTHttpRequestManager requestUploadPictureWithType:type image:image success:^(id  _Nullable responseObject) {
        [self endHud];
        DBLog(@"上传图片：%@",responseObject);
        if (!responseObject) {
            [HTShowUtil showMessage:@"图片保存失败"];
            return ;
        }
        NSString *codeStr = [NSString stringWithFormat:@"%@",responseObject[@"code"]];
        if (![codeStr isEqualToString:@"200"]) {
            [HTShowUtil showMessage:@"图片保存失败"];
            return;
        }
        self.picUrl = @"picurl";
        
    } failure:^(NSError * _Nonnull error) {
        [self endHud];
        [HTShowUtil showMessage:@"图片保存失败"];
    }];
}
- (void)netLoadRegister{
    [self startHud];
    [HTHttpRequestManager requestRegisterWithDrivercar:self.idCard username:self.name cards:self.idCard ismast:@"0" cartype:self.cardType  carnumber:self.license carwm:self.truckType carlength:self.length goas:self.heavy success:^(id  _Nullable responseObject) {
        [self endHud];
        DBLog(@"注册：%@",responseObject);
        if (!responseObject) {
            [HTShowUtil showMessage:@"注册失败"];
            return ;
        }
        NSString *codeStr = [NSString stringWithFormat:@"%@",responseObject[@"code"]];
        if (![codeStr isEqualToString:@"200"]) {
            [HTShowUtil showMessage:responseObject[@"message"]];
            return;
        }
        for (UIViewController * controller in self.navigationController.viewControllers) {
            if ([controller isKindOfClass:[HTMineViewController class]]) {
                [self.navigationController popToViewController:controller animated:YES];
                return;
            }
        }
    } failure:^(NSError * _Nonnull error) {
        [self endHud];
        [HTShowUtil showMessage:@"注册失败"];
    }];
}
- (void)netLoadUserMessage{
    [self startHud];
    [HTHttpRequestManager requestUserMessageSuccess:^(id  _Nullable responseObject) {
        [self endHud];
        DBLog(@"个人信息：%@",responseObject);
        if (!responseObject) {
            [HTShowUtil showMessage:@"获取失败"];
            return ;
        }
        NSString *codeStr = [NSString stringWithFormat:@"%@",responseObject[@"code"]];
        if (![codeStr isEqualToString:@"200"]) {
            [HTShowUtil showMessage:@"获取失败"];
            return;
        }
        self.mineModel = [HTMineModel mj_objectWithKeyValues:responseObject[@"data"]];
        [self configData];
        [self.tableView reloadData];
    } failure:^(NSError * _Nonnull error) {
        [self endHud];
        [HTShowUtil showMessage:@"获取失败"];
    }];
}

@end
